#include "studentstore.h"
#include "init.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include "utils.h"
#include <time.h>

using namespace student;
using namespace utils;

namespace studentstore {
/*添加和修改用户*/
bool addStudent(Student* stu) {
    auto size = sizeof (Student);//学生类的大小
    FILE *file = openfile(studentDatPath, size); //打开文件

    if (stu->ID == -1) { //初始化ID为-1，若ID为-1则表示该学生是新用户
        fseek(file, 0, SEEK_END);//fseek将文件指针指到文件末尾
        auto offset = ftell(file);//ftell得到文件从指针到文件头的大小（offset是文件总大小）
        stu->ID = offset / size; //确定ID大小
    } else { //已存在ID，表示不是新用户可以进行文件修改
        fseek(file, size * stu->ID, SEEK_SET);//将文件指针移到文件第ID个学生后
    }
    fwrite(stu, size, 1, file);//将student内容写入文件
    fclose(file);//关闭文件
    addLog("[addUser] status 0 : Add userID[" + to_string(stu->ID) + "] successfully");
    return 1;//返回1表示添加成功
}

void addMessage(Message* msg) {
    auto size = sizeof (Message);//Message类的大小
    FILE *file = openfile(messageDatPath, size); //打开文件
    fseek(file, 0, SEEK_END);//fseek将文件指针指到文件末尾
//    auto offset = ftell(file);//ftell得到文件从指针到文件头的大小（offset是文件总大小）
//    stu->ID = offset / size; //确定ID大小
    fwrite(msg, size, 1, file);//将message内容写入文件
    fclose(file);//关闭文件
    addLog("[addMessage] status 0 : senderID[" + to_string(msg->sender_id) + "] send a message to receiverID[" + to_string(msg->receiver_id) + "] successfully");
}

vector<Message*> readMessage(int receiver_id) {
    auto size = sizeof (Message);                 //学生类的大小
    FILE *file = openfile(messageDatPath, size);      //打开文件
    fseek(file, 0, SEEK_END);               //fseek将文件指针指到文件末尾
    auto offset = ftell(file);              //ftell得到文件从指针到文件头的大小（offset是文件总大小）
    int count = offset / size;              //确定文件总数
    Message* temp = new Message;                        //新建一个临时储存类型
    memset(temp, 0, sizeof (Message));            //所有信息先赋值为0
    fseek(file, 0, SEEK_SET);               //将指针指到文件头

    vector<Message*> matchList;
    matchList.clear();

    //不使用模糊搜索
    for(int i = 0; i < count; i++) {                             //遍历数据
        fread(temp, size, 1, file);                              //依次读出并对比学号
        if((temp->receiver_id == -2) || (temp->receiver_id == receiver_id) || (temp->sender_id == receiver_id)) { //！！！大坑，不能直接存temp，temp是指针位置最后会跳到文件尾
            Message* temp2 = new Message;                                    //每次新建一个空间储存新找到的数据结构体
            memset(temp2, 0, sizeof (Message));                        //新建的结构体所有信息先赋值为0
            memcpy(temp2, temp, sizeof(Message));                      //把temp内存整体复制到temp2
            matchList.push_back(temp2);
        }

    }
    fclose(file);
    return matchList;
}

//成功0，学生正在借阅-1，学生正在预约 -2
int deleteStudent(int user_id) {
//    cout << "start delete student" << endl;
    Student * user = new Student;   //准确查找
    user = search<Student>(user_id, studentDatPath);

    //返回-1，学生正在借阅
    for(int i = 0; i < MAX_BORROW; i++) {
        if(user->borrow[i] != -1) {
            addLog("[deleteUser] status -1 : The user is borrowing book. Delete userID[" + to_string(user->ID) + "] unsuccessfully");
            return -1;
            break;
        }
    }

    //返回-2，书籍正在被预约
    for(int i = 0; i < MAX_BORROW; i++) {
        if(user->reserve[i] != -1) {
            addLog("[deleteUser] status -2 : The user is reserving book. Delete userID[" + to_string(user->ID) + "] unsuccessfully");
            return -2;
            break;
        }
    }

    //返回0，正常
    deleteItem<Student>(user->ID, studentDatPath);
    addLog("[deleteUser] status 0 : Delete userID[" + to_string(user->ID) + "] successfully");
    return 0;

}

/*构造用户*/
Student* creatStudent(string name, string stu_id, string pwdHash, string pwdSalt, string major) {
    Student* stu = new Student();
    memset(stu, 0, sizeof (Student));//先为所有信息赋值为0
    stu->ID = -1;           //编号
    stu->all_Borrow = 0;
    strcpy(stu->name, &name[0]);
    strcpy(stu->pwdHash, &pwdHash[0]);
    strcpy(stu->pwdSalt, &pwdSalt[0]);
    strcpy(stu->major, &major[0]);
    strcpy(stu->stu_id, &stu_id[0]);

    //将三个数组置-1
    for(int i = 0; i < MAX_BORROW; i++) {
        stu->borrow[i] = -1;
    }
    for(int i = 0; i < MAX_RESERVE; i++) {
        stu->reserve[i] = -1;
    }
    for(int i = 0; i < MAX_STAR; i++) {
        stu->star[i] = -1;
    }

    stu->exist = 1;        //学生存在了
    stu->type = 1;      //用户类型
    return stu;
}

Student* creatStudent() {
    Student* stu = new Student;
    memset(stu, 0, sizeof (Student));//所有信息先赋值为0
    stu->ID = -1;          //编号
    stu->exist = 1;        //学生存在了
    stu->type = 1;      //用户类型
    return stu;
}
//多返回搜索，可调节是否使用模糊搜索,参数为（string 是否使用模糊搜索，string 表中的要搜索的字段，string 搜索关键词，文件路径）
vector<Student*> search_multipleReturn(string fuzzySearchCondition, string field, string searchKey, const char* path) {
    auto size = sizeof (Student);                 //学生类的大小
    FILE *file = openfile(path, size);      //打开文件
    fseek(file, 0, SEEK_END);               //fseek将文件指针指到文件末尾
    auto offset = ftell(file);              //ftell得到文件从指针到文件头的大小（offset是文件总大小）
    int count = offset / size;              //确定文件总学生信息
    Student* temp = new Student;                        //新建一个临时储存类型
    memset(temp, 0, sizeof (Student));            //所有信息先赋值为0
    fseek(file, 0, SEEK_SET);               //将指针指到文件头

    vector<Student*> matchList;
    matchList.clear();

    char* matchField = NULL;
    if(field == "stu_id")
        matchField = temp->stu_id;
    if(field == "name")
        matchField = temp->name;

    //不使用模糊搜索
    if(fuzzySearchCondition == "notFuzzySearch") {
        for(int i = 0; i < count; i++) {                             //遍历数据
            fread(temp, size, 1, file);                              //依次读出并对比学号

            if(strcmp(matchField, searchKey.c_str()) == 0 && temp->exist == 1) {     //！！！大坑，不能直接存temp，temp是指针位置最后会跳到文件尾
                Student* temp2 = new Student;                                    //每次新建一个空间储存新找到的数据结构体
                memset(temp2, 0, sizeof (Student));                        //新建的结构体所有信息先赋值为0
                memcpy(temp2, temp, sizeof(Student));                      //把temp内存整体复制到temp2
                matchList.push_back(temp2);
            }

        }
    }
    //使用模糊搜索
    else if(fuzzySearchCondition == "useFuzzySearch") {
        for(int i = 0; i < count; i++) {                            //遍历数据
            fread(temp, size, 1, file);                             //依次读出并对比学号

            string tempStr = matchField;
            if(tempStr.find(searchKey.c_str()) != tempStr.npos && temp->exist == 1) { //！！！大坑，不能直接存temp，temp是指针位置最后会跳到文件尾
                Student* temp2 = new Student;                                   //每次新建一个空间储存新找到的数据结构体
                memset(temp2, 0, sizeof (Student));                       //新建的结构体所有信息先赋值为0
                memcpy(temp2, temp, sizeof(Student));                     //把temp内存整体复制到temp2
                matchList.push_back(temp2);
            }

        }
    }
    fclose(file);
    return matchList;
}

//将学生加入英雄榜
void addHeroRank(int user_id) {
    auto size = sizeof (HeroRank);//famous类的大小
    time_t timep;
    time(&timep);
    HeroRank* heroRank = new HeroRank;
    heroRank->userID = user_id;
    heroRank->achieveTime = timep;
    FILE *file = openfile(heroRankDatPath, size); //打开文件
    fseek(file, 0, SEEK_END);//fseek将文件指针指到文件末尾
    fwrite(heroRank, size, 1, file);//将已经修改的内容写回文件
    delete heroRank;  //释放中间变量
    fclose(file);

}
}
